package com.bing.controller.open;

import com.bing.Component.Context;
import com.bing.bean.weixin.*;
import com.bing.services.AccountService;
import com.bing.services.UserService;
import com.bing.services.WeiXinService;
import com.bing.services.impl.AbstractCommandService;
import com.bing.utils.JaxbXmlHandler;
import com.bing.utils.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * Created by kaibb on 2014/9/30.
 */

@Controller
@RequestMapping("msg")
public class MsgController {

    @Autowired
    private WeiXinService weiXinService;

    @Autowired
    private AccountService accountService;
    @Autowired
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(MsgController.class);

    @RequestMapping(value = "{url}", method = RequestMethod.GET, produces = {MediaType.TEXT_PLAIN_VALUE})
    @ResponseBody
    public String connWeiXin(@PathVariable String url, @RequestParam String signature, @RequestParam String timestamp, @RequestParam String nonce, @RequestParam String echostr) {
        logger.info("请求接入:[url:{},signature:{},timestamp:{},nonce:{},echostr:{}]", url, signature, timestamp, nonce, echostr);
        Account account = accountService.findByUrl(url);
        if (account == null) {
            logger.info("此账号未注册:{}", url);
            return "";
        }
        if (AccountStatus.active != account.getAccountStatus()) {
            logger.info("此账号未激活:{}", url);
            return "";
        }
        if (SignUtil.checkSignature(account.getToken(), signature, timestamp, nonce)) {
            logger.info("接入[{}/{}]成功.", account.getAccountType(), url);
            return echostr;
        } else {
            logger.error("接入[{}/{}]失败", account.getAccountType(), url);
            return "error";
        }
    }

    @RequestMapping(value = "{url}", method = RequestMethod.POST, consumes = MediaType.TEXT_XML_VALUE)
    @ResponseBody
    public String msg(@PathVariable String url, @RequestHeader HttpHeaders headers, @RequestBody String xml, @RequestParam(required = false) String signature, @RequestParam(required = false) String timestamp, @RequestParam(required = false) String nonce) {
       /* for (String header : headers.keySet()) {
            logger.debug("请求header{}: {}", header, headers.getFirst(header));
        }
*/
        logger.info("接收信息:[url:{},signature:{},timestamp:{},nonce:{},{}]", url, signature, timestamp, nonce, xml);
      /*  if (!SignUtil.checkSignature("abcdefg", signature, timestamp, nonce)){
            return null;
        }*/
        //ReqBaseMsg requestMsg = JAXBXMLHandler.convertToObj(msg);
        Account account = accountService.findByUrl(url);
        if (account == null || AccountStatus.active != account.getAccountStatus()) {
            logger.info("此url:{}未注册",url);
            return "";
        }


        RequestMessage requestMessage = JaxbXmlHandler.convertToObj(xml, RequestMessage.class);
        User user = new User();
        user.setAccount(account);
        user.setOpenId(requestMessage.getFromUserName());
        Context context = new Context();
        context.setRequestMessage(requestMessage);
        context.setAccount(account);
        context.setUser(userService.getUser(user));
        ResponseMessage responseMessage = null;
        switch (requestMessage.getMsgType()) {
            case text:
                context.setCommand(requestMessage.getContent());
                responseMessage = weiXinService.handleCommand(context);
                break;
            case event:
                context.setCommand(AbstractCommandService.TW+MsgType.event);
                responseMessage = weiXinService.handleCommand(context);
                break;
            case image:
                responseMessage = weiXinService.handleImage(context);
                break;
            case voice:

                break;
            case video:

                break;
            case location:
                responseMessage = weiXinService.handleLocation(context);
                break;
            case link:
                break;
            default:
                logger.info("无法处理[{}/{}]信息", account.getAccountType(), url);
                return "";
        }
        String result = "";
        if (responseMessage != null) {
            result = JaxbXmlHandler.convertToXml(responseMessage);
        }
        logger.info("[{}/{}]返回信息:{}", account.getAccountType(), url, result);
        return result;
    }

}
